<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '查看' : !isCreate ? '编辑' : '生成采购单'"
    v-model="visible" class="process-add" fullscreen align-center width="1360px" @close="handleClose">
    <div v-if="visible"
      v-anchors="{ anchorsClass: '.v-title', scrollClass: '.process-add .el-dialog__body', disabled: !isLook }">
      <el-form ref="formRef" :model="form" label-position="left" label-width="96px">
        <div :class="is1688 && 'inline-block'" :style="{ width: is1688 ? '60%' : null }">
          <div class="v-title mb-3">产品信息</div>
          <div class="flex items-center mb-3" v-if="!isLook && !is1688">
            <el-button type="primary" @click="addGoods(goodsRef)"><i class="dk-iconfont icon-Plus" />添加sku</el-button>
            <el-button :loading="loadings.split" @click="handleBatch('split')">拆分生成订单</el-button>
            <el-button @click="handleBatch('delete')"><i class="dk-iconfont icon-Delete" />删除产品</el-button>
            <div class="flex gap-2 ml-auto">
              <div>产品总数量: {{ total.purchase_num }}</div>
              <div>产品总额: ¥{{ total.total_price }}</div>
              <div>总运费: ¥{{ total.tracking_price }}</div>
              <div>总优惠: ¥{{ total.discount_price }}</div>
              <div>采购总成本: ¥{{ total.total_purchase_price }}</div>
            </div>
          </div>
          <vxe-table ref="tableRef" :data="form.sku" size="small" :row-config="{ height: 130 }" show-overflow>
            <vxe-column type="checkbox" width="40"></vxe-column>
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column title="sku" :min-width="180">
              <template #default="{ row }">
                <div>产品sku: {{ row.sku }}</div>
                <el-link type='primary' @click="historyRef.open(row.sku)">
                  <i class="dk-iconfont icon-Tickets" /></el-link>
                <div>自定义sku: {{ row.custom_sku }}</div>
                <el-link type='primary' :href="row.goods_link">产品详情</el-link><br>
                <el-link type='primary'>库存信息</el-link>
              </template>
            </vxe-column>
            <vxe-column title="来源信息" :min-width="180">
              <template #default="{ row }">
                订单来源:
                <div> <el-select v-model="row.order_source" placeholder="请选择" :disabled="disabled">
                    <el-option v-for="(d, i) in options.order_source" :key="i" :label="d.label"
                      :value="d.value"></el-option>
                  </el-select></div>
                来源单号:
                <div> <el-input v-model="row.source_no" placeholder="来源单号" class="w-full" :disabled="disabled" /></div>
              </template>
            </vxe-column>
            <vxe-column title="图片" :min-width="100">
              <template #default="{ row }">
                <div class="flex items-center p-2">
                  <VImage :src="row.main_img" size="80px"></VImage>
                </div>
              </template>
            </vxe-column>
            <vxe-column title="产品名称" :min-width="180">
              <template #default="{ row }">
                <div>{{ row.sku_cn_title }}</div>
              </template>
            </vxe-column>
            <vxe-column title="产品链接" :min-width="140">
              <template #default="{ row }">
                <el-link v-if="row.goods_link_type === 1" type='primary' :href="row.goods_link" target="_blank">
                  <div class="text-2-line">{{ row.goods_link }}</div>
                </el-link>
                <el-link v-else type='primary' class="text-red-600" @click="relevance(row)">
                  <i class="dk-iconfont icon-WarningFilled" />
                  未关联1688
                </el-link>
              </template>
            </vxe-column>
            <vxe-column title="产品属性" :min-width="80">
              <template #default="{ row }">
                <div>尺寸: {{ row.attribute }}</div>
              </template>
            </vxe-column>
            <vxe-column title="数量" :min-width="140">
              <template #header>
                <div>数量</div>
                <VGroup v-if="!isLook && !is1688">
                  <el-input-number v-model="tableForm.purchase_num" :controls="false" clearable :min="0" :step="1"
                    size="small" :precision="0" class="w-full" />
                  <el-button type="primary" size="small" @click="updatePurchaseNum">批更</el-button>
                </VGroup>
              </template>
              <template #default="{ row }">
                <el-input-number v-model="row.purchase_num" :controls="false" clearable :min="0" :step="1" :precision="0"
                  class="w-full" :disabled="disabled" @change="calcUnitPurchasePrice(row)" />
              </template>
            </vxe-column>
            <template v-if="!is_drawback">
              <vxe-column title="产品单价" :min-width="80">
                <template #default="{ row }">
                  <div>{{ row.unit_price }}</div>
                </template>
              </vxe-column>
            </template>
            <template v-else>
              <vxe-column title="税点" :min-width="80">
                <template #default="{ row }">
                  <div>{{ row.tax_rate }}</div>
                </template>
              </vxe-column>
              <vxe-column title="不含税产品单价" :min-width="120">
                <template #default="{ row }">
                  <div>{{ row.unit_price }}</div>
                </template>
              </vxe-column>
              <vxe-column title="含税产品单价" :min-width="120">
                <template #default="{ row }">
                  <div>{{ row.unit_price_tax }}</div>
                </template>
              </vxe-column>
            </template>
            <vxe-column title="运费分摊" :min-width="120">
              <template #header>
                运费分摊 <el-tooltip class="box-item" effect="dark" placement="top">
                  <template #content>
                    1、总运费/产品重量比例/单个sku下单数量；<br>
                    2、可手动更改，但更改后的金额*下单数量要与总运费一致
                  </template>
                  <i class="dk-iconfont icon-QuestionFilled" />
                </el-tooltip>
              </template>
              <template #default="{ row }">
                <el-input-number v-model="row.tracking_price" :controls="false" clearable :min="0" :step="0.01"
                  :precision="2" class="w-full" :disabled="disabled" @blur="trackingChange(row)" />
              </template>
            </vxe-column>
            <vxe-column title="优惠分摊" :min-width="120">
              <template #default="{ row }">
                <el-input-number v-model="row.discount_price" :controls="false" clearable :min="0" :step="0.01"
                  :precision="2" class="w-full" :disabled="disabled" @blur="discountChange(row)" />
              </template>
            </vxe-column>
            <template v-if="!is_drawback">
              <vxe-column title="单个采购成本" :min-width="120">
                <template #default="{ row }">
                  {{ row.unit_purchase_price }}
                </template>
              </vxe-column>
              <vxe-column title="产品总金额" :min-width="120">
                <template #default="{ row }">
                  {{ row.is_drawback ? row.total_price_tax : row.total_price }}
                </template>
              </vxe-column>
              <vxe-column title="采购总成本" :min-width="120">
                <template #default="{ row }">
                  {{ row.is_drawback ? row.total_purchase_price_tax : row.total_purchase_price }}
                </template>
              </vxe-column>
            </template>
            <template v-else>
              <vxe-column title="不含税产品总金额" :min-width="100">
                <template #default="{ row }">
                  {{ row.purchase_num * +row.unit_price }}
                </template>
              </vxe-column>
              <vxe-column title="含税产品总金额" :min-width="100">
                <template #default="{ row }">
                  {{ row.purchase_num * +row.unit_price_tax }}
                </template>
              </vxe-column>
            </template>
            <vxe-column title="预计到货时间" :min-width="180">
              <template #header>
                <div>预计到货时间</div>
                <VGroup v-if="!isLook && !is1688">
                  <el-date-picker v-model="tableForm.expect_delivery_time" placeholder="日期选择" type="date"
                    value-format="YYYY-MM-DD" size="small" class="w-full" />
                  <el-button type="primary" size="small" @click="updateExpectDeliveryTime">批更</el-button>
                </VGroup>
              </template>
              <template #default="{ row }">
                <el-date-picker v-model="row.expect_delivery_time" placeholder="日期选择" type="date"
                  value-format="YYYY-MM-DD" class="w-full" :disabled="disabled" />
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="inline-block w-2/5 pl-3" v-if="is1688">
          <div class="v-title mb-3">1688产品信息</div>
          <vxe-table ref="tableRef" :data="form.sku" size="small" :row-config="{ height: 130 }" show-overflow>
            <vxe-column title="图片" :min-width="100">
              <template #default="{ row }">
                <div class="flex items-center p-2">
                  <VImage :src="row.main_img" size="80px"></VImage>
                </div>
              </template>
            </vxe-column>
            <vxe-column title="商品id/产品名称" :min-width="180">
              <template #default="{ row }">
                <div>{{ row.sku_cn_title }}</div>
                <div>{{ row.sku_cn_title }}</div>
              </template>
            </vxe-column>
            <vxe-column title="产品属性" :min-width="80">
              <template #default="{ row }">
                <div>尺寸: {{ row.attribute }}</div>
              </template>
            </vxe-column>
            <vxe-column title="下单数量" :min-width="140">
              <template #default="{ row }">{{ row.purchase_num }} </template>
            </vxe-column>
            <vxe-column title="价格" :min-width="80">
              <template #default="{ row }">
                <div>单价: {{ row.unit_price }}</div>
                <div>合计: {{ row.unit_price }}</div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="gap-x-10 mt-4"
          :style="{ display: isLook ? 'block' : 'grid', 'grid-template-columns': `repeat(${is1688 ? 4 : 3}, minmax(0, 1fr)) !important` }">
          <div>
            <div class="v-title my-3">基础信息</div>
            <el-form-item label="采购单号" prop="purchase_no">
              <el-input v-if="!isCreate" v-model="form.basic.purchase_no" placeholder="采购单号" class="w-full"
                :disabled="disabled" />
            </el-form-item>
            <el-form-item label="供应商类型" prop="basic.purchase_type"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.basic.purchase_type" :options="options.purchase_type || []" placeholder="供应商类型" select
                filterable clearable :reserve-keyword="false" class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="采购人员" prop="purchase_user_id">
              <VCascader v-model="form.basic.purchase_user_id" placeholder="请选择" filterable clearable
                :disabled="disabled || isCreate" class="w-full" />
            </el-form-item>
            <el-form-item label="备货方式" prop="basic.prepare_type"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.basic.prepare_type" :options="options.prepare_type || []" placeholder="备货方式" select
                filterable clearable :reserve-keyword="false" class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="平台单号" prop="platform_order_no">
              <el-input v-if="!isCreate" v-model="form.basic.platform_order_no" placeholder="平台单号" class="w-full"
                :disabled="disabled" />
            </el-form-item>
            <el-form-item label="目的仓库" prop="basic.destination_warehouse"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.basic.destination_warehouse" type="warehouse156" placeholder="目的仓库" select filterable
                clearable :reserve-keyword="false" class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="是否退税" prop="basic.is_drawback"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <el-radio-group v-model="form.basic.is_drawback" :disabled="disabled">
                <el-radio :value="2">含税</el-radio>
                <el-radio :value="1">不含税</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="物流单号" prop="tracking_data">
              {{ isCreate ? '' : (form.basic.tracking_data || []).map(d => d.tracking_no).join(',') }}
            </el-form-item>
            <el-form-item label="业务状态">
              {{ form.basic.audit_status_name || '待提交' }}
            </el-form-item>
            <el-form-item label="订单备注" prop="remark">
              <el-input v-model="form.basic.remark" placeholder="请输入" type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }" />
            </el-form-item>
          </div>
          <div>
            <div class="v-title mb-3">供应商信息</div>
            <el-form-item label="供应商">
              <el-input v-model="form.supplier.supplier_name" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="供应商类型">
              <el-input v-model="form.supplier.purchase_type_name" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="结算方式">
              <el-input v-model="form.supplier.period_name" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="结算时间">
              {{ form.supplier.settlement_time }}
            </el-form-item>
            <el-form-item label="付款起始日">
              {{ form.supplier.start_payment_time }}
            </el-form-item>
            <el-form-item label="交易方式">
              <el-input v-model="form.supplier.payment_type_name" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="收款账号">
              <el-input v-model="form.supplier.collect_account" disabled class="w-full" />
            </el-form-item>
            <el-form-item label="联系人">
              {{ form.supplier.contact_name }}
            </el-form-item>
            <el-form-item label="联系方式">
              {{ form.supplier.tel }}
            </el-form-item>
            <el-form-item label="供应商负责人">
              {{ form.supplier.director_name }}
            </el-form-item>
            <el-form-item label="是否包邮">
              <v-group>
                <VSelect v-model="form.supplier.free_shipping" :options="options.free_shipping || []" :disabled="isCreate"
                  placeholder="是否包邮" class="w-full" />
                <VSelect v-model="form.supplier.cod_type" :options="options.cod_type || []" :disabled="isCreate"
                  placeholder="是否到付" class="w-full" />
                <el-input-number v-if="form.supplier.free_shipping === 3" v-model="form.supplier.free_amount"
                  controls-position="right" :min="0" :step="0.01" placeholder="金额（满金额包邮）" :disabled="isCreate"
                  :precision="2" class="w-full" />
              </v-group>
            </el-form-item>
          </div>
          <div>
            <div class="v-title mb-3">结算信息</div>
            <el-form-item label="公司主体" prop="settlement.company_id"
              :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
              <VSelect v-model="form.settlement.company_id" :options="options.company_id || []" placeholder="公司主体"
                select filterable clearable :reserve-keyword="false" class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="结算币种" prop="currency">
              <VSelect v-model="form.settlement.currency" :options="options.currency || []" placeholder="结算币种" select filterable
                clearable :reserve-keyword="false" class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="支付账号" prop="alipay_account">
              <VSelect v-model="form.settlement.alipay_account" :options="options.alipay_account || []" placeholder="支付账号"
                select filterable clearable :reserve-keyword="false" class="w-full" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="财务状态" prop="purchase_no">
              {{ form.settlement.finance_status_name || '待申请付款' }}
            </el-form-item>
            <el-form-item label="付款单号" prop="purchase_no">
              {{ (form.settlement.payment_no || []).join(',') }}
            </el-form-item>
            <el-form-item label="产品总额" prop="purchase_no">
              {{ total.total_price }}
            </el-form-item>
            <el-form-item label="总运费" prop="tracking_price">
              <VGroup>
                <el-input-number v-model="form.settlement.tracking_price" :controls="false" :min="0" :step="0.01"
                  :precision="2" class="w-full" :disabled="disabled" />
                <el-button type="primary" v-if="!disabled" @click="updateTracking">分摊</el-button>
              </VGroup>
            </el-form-item>
            <el-form-item label="总优惠" prop="discount_price">
              <VGroup>
                <el-input-number v-model="form.settlement.discount_price" :controls="false" :min="0" :step="0.01"
                  :precision="2" class="w-full" :disabled="disabled" />
                <el-button type="primary" v-if="!disabled" @click="updateDiscount">分摊</el-button>
              </VGroup>
            </el-form-item>
            <el-form-item label="应付金额" prop="purchase_no">
              {{ total.total_purchase_price }}
            </el-form-item>
          </div>
          <div v-if="is1688">
            <div class="v-title mb-3">1688下单核算</div>
            <el-form-item label="买家留言" prop="settlement.company_id">
              <el-input v-model="form.platform.message" placeholder="买家留言" type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }" />
            </el-form-item>
            <el-form-item label="当前账号名称" prop="currency" class="leading-3 h-3">
              {{ form.platform.purchase_account }}
            </el-form-item>
            <el-form-item label="收货信息" prop="alipay_account">
              <div class="flex flex-col gap-1">
                <div class="flex gap-1">
                  <el-input v-model="form.platform.deliver_data.full_name" placeholder="收货人" class="w-full" />
                  <el-input v-model="form.platform.deliver_data.mobile" placeholder="手机号" class="w-full" />
                  <el-button link type="primary" @click="getAddress"><i class="dk-iconfont icon-RefreshRight" />获取</el-button>
                </div>
                <el-input v-model="form.platform.deliver_data.address" placeholder="收货地址" class="w-full" />
                <el-input v-model="form.platform.deliver_data.post" placeholder="邮编" class="w-full" />
              </div>
            </el-form-item>
            <el-form-item label="交易方式" prop="purchase_no">
              <el-radio-group v-model="form.platform.payment_type" :disabled="false">
                <el-radio v-for="(d, i) in options.payment_type || []" :key="i" :value="d.value">{{ d.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="供应商运费" prop="purchase_no" class="leading-3 h-3">
              {{ form.platform.tracking_price }}
            </el-form-item>
            <el-form-item label="供应商优惠" prop="purchase_no" class="leading-3 h-3">
              {{ form.platform.discount_price }}
            </el-form-item>
            <el-form-item label="订单总金额" prop="purchase_no" class="leading-3 h-3">
              {{ form.platform.total_price }}
            </el-form-item>
          </div>
        </div>
        <template v-if="isLook">
          <div class="v-title my-3">日志信息</div>
          <vxe-table :data="form.log" size="small">
            <vxe-column title="操作人" field="create_user"></vxe-column>
            <vxe-column title="操作类型" field="log_type"></vxe-column>
            <vxe-column title="详情" field="log_info" min-width="300"></vxe-column>
            <vxe-column title="操作时间" field="create_time"></vxe-column>
          </vxe-table>
        </template>
      </el-form>
    </div>
    <template #footer>
      <template v-if="isLook">
        <el-button @click="close">关 闭</el-button>
      </template>
      <template v-else>
        <el-button @click="close">取 消</el-button>
        <el-button v-if="is1688" type="primary" :loading="loadings.create" @click="create1688(formRef)">确 定</el-button>
        <el-button v-else type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
      </template>
    </template>
    <Goods ref="goodsRef" @change="goodsChange" />
    <VHistory ref="historyRef" />
    <Relevance ref="relevanceRef" @success="relevanceSuccess" />
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import Goods from '@/components/Goods'
import VHistory from '@/components/VHistory'
import XEUtils from 'xe-utils'
import Relevance from '@/views/product/product/components/Relevance'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})


// 表单处理
const formRef = ref()
const tableRef = ref()
const form = ref({})
const tableForm = ref({})
const isLook = ref(false)
const is1688 = ref(false)

const disabled = computed(() => isLook.value || is1688.value)

const is_drawback = computed(() => form.value.basic?.is_drawback === 2)

const total = computed(() => {
  return (form.value.sku || []).reduce((acc, cur) => {
    acc.purchase_num += +cur.purchase_num
    acc.total_price = +XEUtils.toFixed(+acc.total_price + (is_drawback.value ? +cur.total_price_tax : +cur.total_price), 2)
    acc.tracking_price = +XEUtils.toFixed(+acc.tracking_price + (+(cur.tracking_price || 0) * +cur.purchase_num), 2)
    acc.discount_price = +XEUtils.toFixed(+acc.discount_price + (+(cur.discount_price || 0) * +cur.purchase_num), 2)
    acc.total_purchase_price = +XEUtils.toFixed(+acc.total_purchase_price + (is_drawback.value ? +cur.total_purchase_price_tax : +cur.total_purchase_price), 2)
    return acc
  }, { purchase_num: 0, total_price: 0, tracking_price: 0, discount_price: 0, total_purchase_price: 0 })
})

// 关联1688
const relevanceRef = ref()
const relevance = (row) => {
  relevanceRef?.value.open(row.p_id)
}

const relevanceSuccess = item => {
  form.value.sku.forEach(d => {
    if (d.p_id === item.p_id) {
      d.goods_link = item.goods_link
      d.goods_link_type = item.goods_link_type
    }
  })
}

// 获取1688收货地址
const getAddress = () => {
  api.address().then(res => {
    form.value.platform.deliver_data = res.data
    ElMessage.success('获取成功')
  })
}

// 批量操作
const handleBatch = (name) => {
  const table = tableRef?.value
  const selection = table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const handle = {
    split: async () => {
      if (selection.some(d => !d.ps_id)) {
        ElMessage.warning('请选择采购单已存在的sku')
        return
      }
      loadings.split = true
      api.split({ p_id: form.value.basic.p_id, sku: selection }).then(res => {
        table?.remove(selection)
        ElMessage.success('操作成功')
      }).finally(() => {
        loadings.split = false
      })
    },
    delete: () => {
      table?.remove(selection)
      const { fullData } = table?.getTableData()
      form.value.sku = fullData
    }
  }
  handle[name]()
}


// 批量更改数量
const updatePurchaseNum = () => {
  form.value.sku.forEach(d => {
    d.purchase_num = tableForm.value.purchase_num
    calcUnitPurchasePrice(d)
  })
  // tableForm.value.purchase_num = undefined
}

// 批量更改时间
const updateExpectDeliveryTime = () => {
  form.value.sku.forEach(d => {
    d.expect_delivery_time = tableForm.value.expect_delivery_time
  })
  // tableForm.value.purchase_num = undefined
}

// 计算单个成本
const calcUnitPurchasePrice = (row) => {
  row.unit_purchase_price = +XEUtils.toFixed(row.unit_price + row.tracking_price - row.discount_price, 2)
  row.unit_purchase_price_tax = +XEUtils.toFixed(row.unit_price_tax + row.tracking_price - row.discount_price, 2)
  row.total_purchase_price = +XEUtils.toFixed(row.unit_purchase_price * row.purchase_num, 2)
  row.total_purchase_price_tax = +XEUtils.toFixed(row.unit_purchase_price_tax * row.purchase_num, 2)
  row.total_price = +XEUtils.toFixed(row.unit_price * row.purchase_num, 2)
  row.total_price_tax = +XEUtils.toFixed(row.unit_price_tax * row.purchase_num, 2)
  form.value.sku = [...form.value.sku]
}
// 更新总运费
const trackingChange = async (row) => {
  calcUnitPurchasePrice(row)
  await 1
  form.value.settlement.tracking_price = total.value.tracking_price
}

// 更新总优惠
const discountChange = async (row) => {
  calcUnitPurchasePrice(row)
  await 1
  form.value.settlement.discount_price = total.value.discount_price
}

/**运费 */
// 分摊运费
const updateTracking = () => {
  const { settlement, sku } = form.value
  const { tracking_price } = settlement
  const price = tracking_price / sku.length
  form.value.sku.forEach(d => {
    d.tracking_price = price / d.purchase_num
    calcUnitPurchasePrice(d)
  })
}
/**优惠 */
// 分摊优惠
const updateDiscount = () => {
  const { settlement, sku } = form.value
  const { discount_price } = settlement
  const price = discount_price / sku.length
  form.value.sku.forEach(d => {
    d.discount_price = price / d.purchase_num
    calcUnitPurchasePrice(d)
  })
}

// 商品
const goodsRef = ref()
const addGoods = (goodsRef) => {
  goodsRef.open()
}
const goodsChange = (val) => {
  const { sku } = form.value
  const checkeds = val.filter(d => !sku.some(s => s.p_id === d.p_id)).map(d => {
    d.tracking_price = 0
    d.discount_price = 0
    d.unit_purchase_price = d.unit_price
    return d
  })
  form.value.sku.unshift(...checkeds)
}

// 历史下单价格
const historyRef = ref()

// 打开弹窗
const isCreate = ref(false)
const open = async (id, option = {}) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    basic: {},
    supplier: {},
    settlement: {},
    total: {},
    platform: { deliver_data: [] },
    sku: [],
    log: [],
  }
  tableForm.value = {}
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  if (typeof id === 'number') {
    isLook.value = !!option.isLook
    is1688.value = !!option.is1688
    const params = { p_id: id }
    if (is1688.value) {
      params.type = 'order'
    }
    const res = await api.detail(params)
    if (is1688.value) {
      const message = `${res.data.basic.purchase_no} ${res.data.sku.map(d => `SKU：${d.sku}   数量：${d.purchase_num}套  产品名：${d.sku_cn_title}`).join(' ')}`
      res.data.platform.message = message +
        `
拒收无外箱标识卡及到付件，单箱重量不能超过：15KG，不能混箱，外箱必须要贴外箱标识卡；
外箱标识卡内容包括：
PO号：
SKU：
箱内数量：`
    }
    form.value = res.data
    updateTracking()
  } else {
    const { userInfo } = window
    isCreate.value = true
    const res = await api.getDetail({ pdcs_ids: id })
    form.value.sku = res.data.product.map(d => {
      d.unit_purchase_price = +d.unit_price
      d.unit_purchase_price_tax = +d.unit_price_tax
      d.total_purchase_price = +d.unit_price * d.purchase_num
      d.total_purchase_price_tax = +d.unit_price_tax * d.purchase_num
      d.total_price = +d.unit_price * d.purchase_num
      d.total_price_tax = +d.unit_price_tax * d.purchase_num
      d.tracking_price = 0
      d.discount_price = 0
      const date = new Date()
      date.setDate(date.getDate() + d.purchase_day)
      d.expect_delivery_time = XEUtils.toDateString(date, 'yyyy-MM-dd')
      return d
    })
    form.value.supplier = res.data.supplier
    form.value.basic = {
      is_drawback: 2,
      purchase_user_id: userInfo?.user?.user_id,
      purchase_user_name: userInfo?.user?.en_name,
    }
    form.value.settlement.currency = 1
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (formRef) => {
  if (!await formRef.validate()) return
  for (const key in total.value) {
    const value = total[key]
    form.value.settlement[key] = value
  }
  form.value.settlement.purchase_num = form.value.basic.purchase_num = total.value.purchase_num
  form.value.settlement.discount_price = total.value.discount_price
  form.value.settlement.tracking_price = total.value.tracking_price
  form.value.settlement.total_price = form.value.settlement.total_price_tax = total.value.total_price
  form.value.settlement.total_purchase_price = form.value.settlement.total_purchase_price_tax = total.value.total_purchase_price
  const { basic, settlement, sku } = form.value
  if (isCreate.value) {
    form.value.sku.forEach(d => {
      // 总金额
      d.total_price = +d.purchase_num * +d.unit_price
      d.total_price_tax = +d.purchase_num * +d.unit_price_tax
    })
  }
  loadings.create = true
  await 1
  api[isCreate.value ? 'create' : 'edit']({ basic, settlement, sku }).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}
const create1688 = () => {
  const { basic: { p_id }, platform } = form.value
  const { message, payment_type, deliver_data } = platform
  api.order({ p_id, message, payment_type, deliver_data }).then(res => {
    ElMessage.success('下单成功')
    emit('success')
  })
}

defineExpose({ open })
</script>